<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: {2021/1/7}
 * Time: {16:44}
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\common\business;

use app\common\model\mysql\AdminUser as ModelObj;
use think\Exception;
use think\facade\Log;
use think\facade\Session;

class AdminUser extends Base
{
    protected $modelObj = null;

    public function __construct()
    {
        $this->modelObj = new ModelObj();
    }

    /**
     * @param array $data
     * @return array|bool
     * @throws Exception
     */
    public function getAdminUserByAdminUser(array $data = [])
    {
        if (empty($data)) {
            return false;
        }
        //验证
        $validate = (new \app\common\validate\AdminUser());
        if (!$validate->check($data)) {
            throw new Exception($validate->getError());
        }
        try {
            $userObj = $this->modelObj->getAdminUserByAdminUser($data['username']);
        } catch (\Exception $e) {
            Log::error("getAdminUserByAdminUser:" . $e->getMessage());
            throw new Exception("查询数据发生错误");
        }
        if (!$userObj) {
            throw new Exception("用户信息不存在");
        }
        //判断用户名和密码是否正确
        $user = $userObj->toArray();
        $md5 = md5($data['password'] . $user['code']);
        if ($md5 != $user['password']) {
            throw new Exception("用户名和密码输入错误");
        }
        $update_data = [
            "last_login_time" => time(),
            "last_login_ip" => ip2long(request()->ip())
        ];
        try {
            $res = $userObj->save($update_data);
        } catch (\Exception $e) {
            Log::error("update_admin" . $e->getMessage());
            throw new Exception("发生错误");
        }
        if ($res) {
            //记录session
            Session::set(config('admin.admin_session_key'), md5(http_build_query($user)) . "-" . $user['id'] . "-" . md5(date('y-m-d')));
            return true;
        } else {
            throw new Exception("内部异常!登录失败");
        }
    }
}